<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\AdminroleRequest;
use App\Models\AdminPermission;
use App\Models\AdminRole;
use Illuminate\Http\Request;
use Auth;

class AdminRolesController extends Controller
{
    public function index()
    {
        return AdminRole::get();
    }

    public function store(AdminroleRequest $request)
    {
        $adminRole = AdminRole::create($request->only('name', 'description', 'status'));
        return $adminRole;
    }

    public function edit(AdminRole $adminRole)
    {
        return $adminRole;
    }

    public function update(AdminroleRequest $request, AdminRole $adminRole)
    {
        $adminRole->update($request->only('name', 'description', 'status'));
        return $adminRole;
    }

    public function destroy(AdminRole $adminRole)
    {
        $adminRole->delete();

        // 关联用户、权限
        $adminRole->users()->detach();
        $adminRole->permissions()->detach();
    }

    /**
     * 分配权限
     *
     * @param Request $request
     * @param Role $role
     * @return array
     */
    public function givePermission(Request $request, AdminRole $adminRole)
    {
        if ($request->isMethod('post')) {
            return $adminRole->permissions()->sync($request->permissions);
        }
        return [
            'permissions' => AdminPermission::get(['id', 'name', 'title', 'pid']),
            'myPermissions' => $adminRole->permissions()->get()->pluck('id'),
        ];
    }


}